﻿using System;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using Application = System.Windows.Forms.Application;
using Word = Microsoft.Office.Interop.Word;

namespace Связь_с_БД
{
    class PrintDocumentCertificate9
    {

        public PrintDocumentCertificate9(DataGridViewRow dataGridViewRow)
        {
            _dataGridViewRow = dataGridViewRow;
            _certification9Replace = new string[8];
            _FIO = new string[3];
        }

        public bool IsClosed; 

        private readonly string filePath = @"\PatternDocuments\certificate9.docx";

        private readonly string[] _certification9 = {
                                                        "{datedatedatedatedateda}",
                                                        "{namenamenamenamenamenamenamnamen}",
                                                        "{famfamfamfamfamfamfamfamfamfamfamafmafmaff}",
                                                        "{otcotcotcotcotcotcotcotcotcotcotcotcotcotcotctocto}",
                                                        "{grogrogrogrogrogrogrogrogrogrogrogrogrogrogrogrogrogr}",
                                                        "{COURS}",
                                                        "{facfacfacfacfacfacfacfacfacfacfacfacfacfacfacfacfacafacf}",
                                                        "{formformformformformformformformformformformforfmformformformfor}"
                                                    };

        private string[] _certification9Replace;
        private DataGridViewRow _dataGridViewRow;
        private string[] _FIO;

        private void SetCertification9Values(DataGridViewRow dgvr)
        {
            SplitFIO(dgvr.Cells[27].Value.ToString());

            _certification9Replace[0] = InsertTextInCenter(MakeFormatDate(DateTime.Today.ToShortDateString()),
                                                           _certification9[0]);
            _certification9Replace[1] = InsertTextInCenter(_FIO[0], _certification9[1]);
            _certification9Replace[2] = InsertTextInCenter(_FIO[1], _certification9[2]);
            _certification9Replace[3] = InsertTextInCenter(_FIO[2], _certification9[3]);
            _certification9Replace[4] = InsertTextInCenter(dgvr.Cells[22].Value.ToString(),_certification9[4]);
            _certification9Replace[5] = InsertTextInCenter(GetNumberCourse(dgvr.Cells[22].Value.ToString()),
                                                           _certification9[5]);
            _certification9Replace[6] = InsertTextInCenter("ЭОиМ",_certification9[6]);
            _certification9Replace[7] = InsertTextInCenter(dgvr.Cells[18].Value.ToString(), _certification9[7]);
        }

        private string GetNumberCourse(string str)
        {
            string result;
            int index = str.IndexOf("-");
            index++;
            result = str.Substring(index, 1);
            return result;
        }

        private string InsertTextInCenter(string str, string sourceString)
        {
            string result = string.Empty;
            if (str.Length > sourceString.Length)
                return null;
            if (str.Length == sourceString.Length)
                return str;
            
            double w = str.Length/2;
            double centerPositionStr = Math.Truncate(w);
            int cenPosStr = Convert.ToInt32(centerPositionStr);

            double ww = sourceString.Length/2;
            double centerPositionSource = Math.Truncate(ww);
            int cenPosSource = Convert.ToInt32(centerPositionSource);
            
            int res = cenPosSource - cenPosStr;
            
            int j = 0;
            for(int i=0;i<sourceString.Length;i++)
            {
                if( (i<=res) || i>(res+str.Length) ) result += " ";
                else
                {
                    result += str[j];
                    j++;
                }
            }
            return result;
        }

        private string MakeFormatDate(string date)
        {
            string result = string.Empty;
            char[] mas = date.ToCharArray();
            result += "\"";
            result += mas[0];
            result += mas[1];
            result += "\"";
            result += " ";
            result += " ";
            result += " ";
            result += mas[3];
            result += mas[4];
            result += " ";
            result += " ";
            result += " ";
            //result += ".";
            result += mas[6];
            result += mas[7];
            result += mas[8];
            result += mas[9];
            return result;
        }

        private void SplitFIO(string str)
        {
            string[] result;
            result = str.Split(string.Empty.ToCharArray());
            _FIO = result;
        }

        private void ReplaceText(string text, string replaceText, Document worddocument, _Application wordapp)
        {
            Object start = 0;
            Object end = worddocument.Characters.Count;
            Word.Range wordrange = worddocument.Range(ref start, ref end);
            wordrange.TextRetrievalMode.IncludeHiddenText = false;
            wordrange.TextRetrievalMode.IncludeFieldCodes = false;

            int beginphrase = 0;
            beginphrase = wordrange.Text.IndexOf(text);
            start = beginphrase;
            end = beginphrase + text.Length;
            wordrange = worddocument.Range(ref start, ref end);

            object unit;
            object count;
            object extend;
            //ставим курсор в начало документа
            unit = Word.WdUnits.wdStory;
            extend = Word.WdMovementType.wdMove;
            wordapp.Selection.HomeKey(ref unit, ref extend);

            //переходим к началу нужной фразы
            unit = Word.WdUnits.wdCharacter;
            extend = Word.WdMovementType.wdMove;
            count = beginphrase;
            wordapp.Selection.MoveRight(ref unit, ref count, ref extend);

            //выделяем это слово
            unit = Word.WdUnits.wdCharacter;
            count = text.Length;
            extend = Word.WdMovementType.wdExtend;
            wordapp.Selection.MoveRight(ref unit, ref count, ref extend);

            wordapp.Options.Overtype = false;
            wordapp.Selection.Font.Name = @"Times New Roman";
            wordapp.Selection.Font.Size = 11;
            wordapp.Selection.Font.Underline = WdUnderline.wdUnderlineSingle;
            wordapp.Selection.Font.Color = WdColor.wdColorBlack;
            wordapp.Selection.TypeText(replaceText);
        }

        public void InsertInDocument()
        {
            var wordapp = new Word.Application();
            wordapp.DocumentBeforeClose += WordappDocumentBeforeClose;
            string FilePath = Application.StartupPath + filePath;
            try
            {
                var worddoc = wordapp.Documents.Open(FilePath);
                SetCertification9Values(_dataGridViewRow);
                for (int i = 0; i < _certification9Replace.Length; i++)
                    ReplaceText(_certification9[i], _certification9Replace[i], worddoc, wordapp);

                object nameFormat =
                    WdSaveFormat.wdFormatDocumentDefault;
                worddoc.SaveAs(Application.StartupPath + "\\okok", nameFormat);
                wordapp.Visible = true;
                IsClosed = false;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
                wordapp.Quit();
            }
        }

        private void WordappDocumentBeforeClose(Document document,ref bool cancel)
        {
            IsClosed = true;
        }
    }
}
